package com.chapter20.demo6;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class FileOperation {
    private final Path path;
    //ReentrantReadWriteLock是ReadWriteLock接口的实现类。
    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock readLock = rwLock.readLock();
    private final Lock writeLock = rwLock.writeLock();
    
    private final Charset cs = Charset.forName("GBK");

    public FileOperation(String fileName) {
        path = new File(fileName).toPath();
    }
    
    public String read(){
        //加读锁
        readLock.lock();
        List<String> data =null;
        try {
            data = Files.readAllLines(path, cs);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            readLock.unlock(); //释放读锁
        }
        return data.toString();
    }


    public void write(byte[] data){
        //加写锁
        writeLock.lock();
        try {
            Files.write(path,data, (OpenOption) cs, StandardOpenOption.APPEND);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            writeLock.unlock(); //释放读锁
        }
    }
}
























